import tkinter as tk
import pymongo


def link():
    global login_col
    global bangumi_col
    global extra_col
    my_client = pymongo.MongoClient('mongodb://localhost:27017/')
    mydb = my_client.bilibilitest
    login_col = mydb['login']
    bangumi_col = mydb['jp_bangumi_info']
    extra_col = mydb['extra_series_info']


def clear_click_listen():
    user.set('')
    password.set('')
    text_user.focus()


def sure_click_listen():
    my_user = text_user.get()
    my_password = text_password.get()
    my_query = {'login_name': my_user, 'password': my_password}
    result = login_col.find(my_query)
    if result.count() == 0:
        hint.set('用户名或密码错误')
    else:
        hint.set('')
        login_window.destroy()
        homepage(my_user)


def login():
    global login_window
    global user
    global password
    global hint
    global text_user
    global text_password
    global label_hint
    window_tile = 'login'
    window_size = '250x130'
    # 窗口左侧和上侧到屏幕的距离
    margins = '640+330'
    # 创建界面对象
    login_window = tk.Tk()
    # 设置窗口标题
    login_window.title(window_tile)
    # 设置窗口大小
    login_window.geometry(window_size + '+' + margins)
    label_user = tk.Label(login_window, text='用户名：', font=('宋体', 10))
    label_user.grid(column=0, row=0, pady=10)
    # 用户名
    user = tk.StringVar()
    # user.set('请输入用户名...')
    text_user = tk.Entry(login_window, textvariable=user)
    # text_user.bind('<FocusIn>', lambda fuc: text_user.delete('0', 'end'))
    text_user.grid(column=1, row=0, columnspan=2, pady=10)
    # 密码
    label_password = tk.Label(login_window, text='密码：', font=('宋体', 10))
    label_password.grid(column=0, row=1)
    password = tk.StringVar()
    # password.set('请输入密码...')
    text_password = tk.Entry(login_window, textvariable=password)
    # text_password.bind('<FocusIn>', lambda fuc: text_password.delete('0', 'end'))
    text_password.grid(column=1, row=1, columnspan=2)
    # 按钮
    btn_sure = tk.Button(login_window, text='登录', font='宋体, 10', command=sure_click_listen)
    btn_sure.grid(column=1, row=2, pady=10)
    btn_clear = tk.Button(login_window, text='清除', font='宋体, 10', command=clear_click_listen)
    btn_clear.grid(column=2, row=2, pady=10)
    # 提示标签
    hint = tk.StringVar()
    hint.set('')
    label_hint = tk.Label(login_window, textvariable=hint, font=('宋体', 10))
    label_hint.grid(column=1, row=3, columnspan=2)
    # 窗口循环运行
    login_window.mainloop()


def self_query():
    global btn_status
    # 控件互锁
    if btn_status == -1:
        self_query_frame()
    if btn_status == 1:
        rd1.destroy()
        rd2.destroy()
        btn_query.destroy()
        auto_result_text.destroy()
        auto_scroll_y.destroy()
        auto_scroll_x.destroy()
        self_query_frame()


def auto_query():
    global btn_status
    # 控件互锁
    if btn_status == -1:
        auto_query_frame()
    if btn_status == 0:
        search_entry.destroy()
        btn_search.destroy()
        self_scroll_x.destroy()
        self_scroll_y.destroy()
        self_result_text.destroy()
        auto_query_frame()


def self_query_frame():
    global btn_status
    global search_entry
    global btn_search
    global self_scroll_x
    global self_scroll_y
    global self_result_text
    # 输入行
    search_entry = tk.Entry(window, width=30)
    search_entry.grid(column=2, row=2, columnspan=4, padx=5, sticky='W', ipadx=20)
    # 搜索按钮
    btn_search = tk.Button(window, text='搜索', command=search_click_listen, relief='raised')
    btn_search.grid(column=6, row=2, padx=5, sticky='W', ipadx=20)
    # 结果文本框
    # 默认为垂直滚动条
    self_scroll_y = tk.Scrollbar(window, relief=tk.RAISED)
    self_scroll_y.grid(column=8, row=3)
    # 设置水平滚动条
    self_scroll_x = tk.Scrollbar(window, orient=tk.HORIZONTAL, relief=tk.RAISED)
    self_scroll_x.grid(column=2, row=4, columnspan=4)
    # wrap设置文本不自动换行以唤起水平滚动条
    self_result_text = tk.Text(window, width=60, height=15, relief=tk.SUNKEN, yscrollcommand=self_scroll_y.set,
                               xscrollcommand=self_scroll_x.set, wrap=tk.NONE)
    # 当超过文本框的规定长度之后会唤醒滚动条
    self_scroll_y.config(command=self_result_text.yview())
    self_scroll_x.config(command=self_result_text.xview())
    self_result_text.grid(column=1, row=3, columnspan=6, pady=10, sticky='W')
    btn_status = 0


def auto_query_frame():
    global btn_status
    global rd1
    global rd2
    global btn_query
    global status
    global auto_scroll_x
    global auto_scroll_y
    global auto_result_text
    status = tk.IntVar()
    rd1 = tk.Radiobutton(window, text='2022', variable=status, value=0)
    rd1.grid(column=2, row=2, ipadx=30, columnspan=2, sticky='W')
    rd2 = tk.Radiobutton(window, text='电影', variable=status, value=1)
    rd2.grid(column=4, row=2, ipadx=30, columnspan=2, sticky='W')
    btn_query = tk.Button(window, text='查询', command=radio_button_listen)
    btn_query.grid(column=6, row=2, ipadx=20, columnspan=2, pady=5)
    auto_scroll_y = tk.Scrollbar(window, relief=tk.RAISED)
    auto_scroll_y.grid(column=6, row=3, rowspan=2)
    auto_scroll_x = tk.Scrollbar(window, relief=tk.RAISED, orient=tk.HORIZONTAL)
    auto_scroll_x.grid(column=2, row=4, columnspan=4)
    auto_result_text = tk.Text(window, width=40, height=15, relief=tk.SUNKEN, yscrollcommand=auto_scroll_y.set,
                               xscrollcommand=auto_scroll_x.set, wrap=tk.NONE)
    auto_result_text.grid(column=2, row=3, columnspan=6, pady=10, sticky='W')
    auto_scroll_y.config(command=auto_result_text.yview())
    auto_scroll_x.config(command=auto_result_text.xview())
    btn_status = 1


def search_click_listen():
    # 根据用户输入前缀查找番剧信息(bangumi集合和series集合同时查找)
    # 正则表达式进行模糊查找
    self_result_text.delete('0.0', tk.END)
    my_search = search_entry.get()
    my_query = {'title': {'$regex': my_search + '.{0,10}'}}
    # 默认返回3条消息
    my_result = bangumi_col.find(my_query)
    if my_result.count() == 0:
        self_result_text.insert(tk.END, '搜索结果为0条！\n请改变搜索内容')
    else:
        for item in my_result:
            insert_to_self_text(item)
            series_num = item['bangumi_id']
            series_query = {'series_id': series_num}
            series_result = extra_col.find(series_query)
            if series_result.count() != 0:
                for series in series_result:
                    insert_to_self_text(series)


def insert_to_self_text(info):
    temp = '\n   '
    if info['category'] == 'bangumi':
        if info['is_finished']:
            self_result_text.insert(tk.END, info['title'] + temp + '已完结' + temp
                                    + '共' + info['episode_num'] + '集' + temp + '当前评分：'
                                    + info['score'] + temp + '主页：' + info['homepage'] + '\n' * 2)
        else:
            self_result_text.insert(tk.END, info['title'] + temp + '连载中' + temp
                                    + info['total_fan'] + '人追番' + temp + '当前评分：'
                                    + info['score'] + temp + '主页：' + info['homepage'] + '\n' * 2)
    else:
        self_result_text.insert(tk.END, info['title'] + temp + info['duration'] + temp
                                + info['total_play'] + temp + '当前评分：' + info['score']
                                + temp + '主页：' + info['homepage'] + '\n' * 2)


def radio_button_listen():
    auto_result_text.delete('0.0', tk.END)
    # 如果是1，选择的是电影
    if status.get():
        my_query = {'category': 'movie'}
        movie_result = bangumi_col.find(my_query)
        if movie_result.count() != 0:
            for item in movie_result:
                tag = ''
                length = len(item['tags'])
                for i in range(0, length):
                    if i == length-1:
                        tag += item['tags'][i]
                    else:
                        tag += item['tags'][i] + ','
                auto_result_text.insert(tk.END, item['title'] + '  ' + tag + '  ' + item['total_screen_comment'] + '弹幕'
                                        + '\n'*2)
    else:
        my_query = {'release': {'$regex': '2022'+'.{0,10}'}}
        year_result = bangumi_col.find(my_query).sort('release', -1)
        if year_result.count != 0:
            for item in year_result:
                auto_result_text.insert(tk.END, item['title'] + '  ' + item['release'] + '\n'*2)


def homepage(my_user):
    global window
    window = tk.Tk()
    window.title('homepage')
    window.geometry('600x450+640+330')
    wel_text = '欢迎回来! ' + my_user
    welcome_label = tk.Label(window, text=wel_text, font=('宋体', 10), width=20)
    welcome_label.grid(column=0, row=0, pady=5, columnspan=2, sticky='W')
    tk.Label(window, text='', width=10).grid(column=0, row=1, columnspan=2, sticky='W')
    btn_self_select = tk.Button(window, text='自主查询', font=('宋体', 10), relief='raised', command=self_query)
    btn_self_select.grid(column=2, row=1, pady=10, padx=5,  ipadx=30, columnspan=2, sticky='W')
    btn_auto_select = tk.Button(window, text='条件查询', font=('宋体', 10), relief='raised', command=auto_query)
    btn_auto_select.grid(column=4, row=1, pady=10, padx=5, ipadx=30, columnspan=2, sticky='W')

    window.mainloop()


if __name__ == '__main__':
    btn_status = -1
    link()
    login()
